
class MySingleLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//代表链表的头结点

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void display(ListNode newHead) {
        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void addFirst(int val) {
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
    }

    public ListNode partition(int x) {
        if (head == null) {
            return null;
        }
        // write code here
        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;

        ListNode cur = head;
        while (cur != null) {
            if (cur.val < x) {
                //第一次插入
                if (bs == null) {
                    bs = be = cur;
                } else {
                    be.next = cur;
                    be = be.next;
                }
                cur = cur.next;
            } else {
                if (as == null) {
                    //第一次输入
                    as = ae = cur;
                } else {
                    ae.next = cur;
                    ae = ae.next;
                }
                cur = cur.next;
            }
        }
        //第一部分是不是为空，如果空则返回第二部分，如果不为空，则进行拼接
        if (bs == null) {
            return as;
        }
        //进行拼接
        be.next = as;
        //后半部分不为空，把后半部分最后一个节点置为空
        if (as != null) {
            ae.next = null;
        }
        return bs;
    }
}

public class Demo2_6 {
    //链表分割
    //现有一链表的头指针 ListNode* head，给一定值x，
    //编写一段代码将所有小于x的结点排在其余结点之前，且不能改变原来的数据顺序，
    //返回重新排列后的链表的头指针。
    public static void main(String[] args) {
        MySingleLinkedList msl = new MySingleLinkedList();
        msl.addFirst(11);
        msl.addFirst(15);
        msl.addFirst(6);
        msl.addFirst(8);
        msl.addFirst(20);
        MySingleLinkedList.ListNode retHead = msl.partition(12);
        msl.display(retHead);
    }

}
